#include "pwext.hpp"
#include <list>

// [[ex03cf]]
// DEBUG descr A simple barrier implemented with a hold.
// data used by the workers, its contents is not
// important here
class data;

class worker : public pw::pwthread
{
public:
	worker(data *d, pw::hold *inith) :
		data_(d), inithold_(inith)
	{ }

	virtual void *execute()
	{
		// ... initialize ...
		inithold_->release();
		// .. continue the normal work
		return 0;
	}

protected:
	data *data_;
	pw::hold *inithold_;
};

// the function running in the control thread,
// processes a list of data in parallel
void control(std::list<data *> &dlist)
{
	pw::hold initworkers;
	std::list <worker *> workers;

	for (std::list<data *>::iterator it = dlist.begin(); 
			it != dlist.end(); ++it) {
		initworkers.acquire();
		worker *w = new worker(*it, &initworkers);
		workers.push_back(w);
		w->start();
	}

	initworkers.wait();
	// all workers are known to have completed the
	// initialization ...
	// ... continue ...
	// DEBUG {
	for (std::list<worker *>::iterator it = workers.begin(); it != workers.end(); ++it) {
		(*it)->join();
		delete (*it);
	}
	// DEBUG }
}
// END

// DEBUG {
class data {
public:
	int x_;
};

int main()
{
	std::list<data *> dd;
	dd.push_back(new data);
	dd.push_back(new data);
	dd.push_back(new data);
	control(dd);
	while(!dd.empty()) {
		delete dd.front();
		dd.pop_front();
	}
	return 0;
}
// DEBUG }
